package ddz.db;

import ch.qos.logback.classic.Logger;
import com.kaka.util.ResourceUtils;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.util.Properties;

/**
 * 数据库持久化映射处理类，全局单例
 *
 * @author zhoukai
 */
public class Mybatis {

    private SqlSessionFactory sqlSessionFactory;
    private static final Mybatis instance = new Mybatis();

    private final Logger logger = (Logger) LoggerFactory.getLogger(Mybatis.class);

    private InputStream getConfig() {
        String path = ResourceUtils.getClassLoaderPath(Mybatis.class);
        File file = new File(path + "/sys-config/db.properties");
        InputStream is = null;
        if (!file.exists()) {
            is = ResourceUtils.getResourceAsStream("sys-config/db.properties", Mybatis.class);
            if (is == null) return null;
        } else {
            try {
                is = new FileInputStream(file);
            } catch (FileNotFoundException e) {
                logger.error(e.getLocalizedMessage(), e);
            }
        }
        return is;
    }

    /**
     * 私有构造方法，不允许外部创建对象
     */
    private Mybatis() {
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        try (InputStream is = Resources.getResourceAsStream(classLoader, "mybatis3-config.xml")) {
            Properties dbProps = new Properties();
            try (InputStream dbPropsStream = getConfig()) {
                dbProps.load(dbPropsStream);
            }
            if (!dbProps.isEmpty()) {
                sqlSessionFactory = new SqlSessionFactoryBuilder().build(is, "hikari", dbProps);
            } else {
                sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
            }
        } catch (IOException ex) {
            logger.error("无法读取mybatis3-config.xml配置", ex);
        }
    }

    /**
     * 获取全局唯一实例
     *
     * @return 唯一实例
     */
    public static Mybatis getInstance() {
        return instance;
    }

    /**
     * 获取数据库操作管道
     *
     * @return
     */
    public synchronized SqlSessionFactory getSqlSessionFactory() {
        return sqlSessionFactory;
    }
}
